import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col} from 'antd';
import {FORM_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {proformaInvoiceStatus} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from './DealerSelectPanel';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import routes from './routes';
import {getDealersQuickly} from './api';
const FormItem = Form.Item;
const proformaInvoiceStatusList = proformaInvoiceStatus.toList(language);
class QueryPanel extends React.PureComponent {
    state = {
        data: {},
        showDealerSelectPanel: false,
    }

    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
    onSelectDealer = data => {
        this.props.onConditionsChange('dealerId', data.id);
        this.props.onQueryDealerChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
        this.setState({
            showDealerSelectPanel: false
        });
    }
    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onCloseDealerSelectPanel = () => {
        this.setState({showDealerSelectPanel: false});
    }
    render() {
        const operations = [];
        const {data} = this.state;
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;

        if(hasPermissions(this.props.permissions, PERMISSION.historySearch))
            operations.push(<Button key="historySearch" href={`#${routes.historyQuery.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.historySearch',
                defaultMessage: '历史查询'
            })}</Button>);
        
        if(hasPermissions(this.props.permissions, PERMISSION.add))
            operations.push(<Button key="add" type="primary" href={`#${routes.add.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.add',
                defaultMessage: '新增'
            })}</Button>);

        return (
            <Form className="form-standard">
                <Row>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.partOrderCode',
                                defaultMessage: '订单编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="partOrderCode"
                                value={this.props.conditions.partOrderCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    {!this.props.isDealerUser &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.dealerCode',
                                    defaultMessage: '总代编号'
                                })}
                                {...FORM_OPTIONS.item} >
                                <SearchSelect
                                    allowClear
                                    value={dealerInfo}
                                    placeholder={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.pleaseQuery',
                                        defaultMessage: '请输入查询'
                                    })}
                                    onSelect={this.onSelectDealer}
                                    onSearch={this.onSearchDealer}
                                    keyIndex="id"
                                    labelMap={this.dealerLabelMap}
                                    onClickSearchBtn={this.onClickSearchDealerBtn} />
                            </FormItem>
                        </Col>
                    }
                    {this.props.initEnum.brands && this.props.initEnum.brands.length > 1 &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brandId',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.conditions.brandId}
                                    options={this.props.initEnum.brands}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    }
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.partOrderTypeId',
                                defaultMessage: '订单类型'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partOrderTypeId"
                                value={this.props.conditions.partOrderTypeId}
                                options={this.props.initEnum.partSaleOrderTypes}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'queryPanel.form.status',
                            defaultMessage: '状态'
                        })} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                id="status"
                                allowClear={true}
                                value={this.props.conditions.status}
                                onChange={this.handleFilterChange}
                                options={proformaInvoiceStatusList.filter(d => d.value !== -1)} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.customerOrderCode',
                                defaultMessage: '客户订单号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="customerOrderCode"
                                value={this.props.conditions.customerOrderCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.submitTime',
                                defaultMessage: '提报日期'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DateRangePicker name="submitTime" value={this.props.conditions.submitTime}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                </Row>
                
                <Row>
                    <Col span={6}>
                        <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.props.onResetClick}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.reset',
                                defaultMessage: '重置'
                            })}
                        </Button>
                    </Col>
                    <Col span={18} className="col-align-right">
                        {operations}
                    </Col>
                </Row>
                {
                    this.state.showDealerSelectPanel &&
                    <DealerSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onCloseDealerSelectPanel}
                        onSelect={this.onSelectDealer} />
                }
            </Form>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    initEnum: PropTypes.object.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onQueryDealerChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    intl: PropTypes.object,
    queryDealer: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    resetQueryPanel,
    querySearch,
    saveQueryDealer
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const partSaleOrderTypes = initData.partSaleOrderTypes ? initData.partSaleOrderTypes.map(item => ({
            text: `${item.typeName}`,
            value: item.id
        })) : [];
        return {
            brands,
            partSaleOrderTypes
        };
    }
);

const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    initEnum: getInitData(state),
    conditions: getConditions(state),
    queryDealer: getQueryDealer(state),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onQueryDealerChange: data => dispatch(saveQueryDealer(data)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
